package com.ouc.pampas;
import com.github.jknack.handlebars.io.AbstractTemplateLoader;
import com.github.jknack.handlebars.io.TemplateSource;
import com.github.jknack.handlebars.io.URLTemplateSource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import javax.servlet.ServletContext;
import org.apache.commons.lang3.Validate;

public class GreatTemplateLoader extends AbstractTemplateLoader {
	private ServletContext servletContext;

	public GreatTemplateLoader(ServletContext servletContext, String prefix, String suffix) {
		this.servletContext = servletContext;
		setPrefix(prefix);
		setSuffix(suffix);
	}

	public TemplateSource sourceAt(String location) throws IOException {
		Validate.notEmpty(location, "The uri is required.", new Object[0]);
		URL resource = getResource(location);
		if (resource == null) {
			throw new FileNotFoundException(location);
		}
		return new URLTemplateSource(resource.toString(), resource);
	}

	private URL getResource(String location) throws IOException {
		if (Protocol.analyze(location) == Protocol.SERVLET) {
			String uri = resolve(Protocol.removeProtocol(location, Protocol.SERVLET));
			return this.servletContext.getResource(uri);
		}
		String home = ThreadVars.getApp().getAssetsHome();
		if (location.startsWith("component:")) {
			location = "components/" + normalize(location.substring(10)) + "/view";
		} else {
			location = "views/" + normalize(location);
		}
		String uri = home + location + getSuffix();
		switch (Protocol.analyze(uri).ordinal()) {
		case 1:
		case 2:
			return new URL(uri);
		case 3:
			File file = new File(uri);
			return file.exists() ? file.toURI().toURL() : null;
		case 4:
			return this.servletContext.getResource(Protocol.removeProtocol(uri, Protocol.SERVLET));
		}
		throw new UnsupportedOperationException("template loader only support [HTTP, FILE, SERVLET] protocol");
	}
}
